//
//  GQRankTwoLevelViewController.m
//  TingMusic
//
//  Created by sunny on 16/4/20.
//  Copyright © 2016年 sunny. All rights reserved.
//

#import "GQRankTwoLevelViewController.h"
#import "GQRankListCell.h"
#import "GQRankItem.h"
#import <UIImageView+WebCache.h>
#import "GQRankSongListItem.h"
#import "GQRankBillboardItem.h"
#import <AVFoundation/AVFoundation.h>


@interface GQRankTwoLevelViewController () <UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *updateTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalSongsLabel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *Title_Label;
@property (weak, nonatomic) IBOutlet UIButton *backButton;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imageViewConstraint;
@property (nonatomic,assign)CGFloat lastOffsetY;
@property (nonatomic,strong)GQRankBillboardItem *billboardItem;
@property (nonatomic,strong)NSArray *itemArrays;

/** 播放器 */
@property (nonatomic, strong)AVPlayer *player;
@property (nonatomic,strong)NSArray *songInfoArray;

@end

static NSString *ID = @"Cell";
@implementation GQRankTwoLevelViewController

- (NSArray *)itemArrays
{
    if (!_itemArrays) {
        _itemArrays = [NSArray array];
    }
    return _itemArrays;
}

- (NSArray *)songInfoArray
{
    if (_songInfoArray == nil) {
        _songInfoArray = [NSArray array];
    }
    return _songInfoArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = YES;
    self.tableView.rowHeight = 100;
    self.tableView.contentInset = UIEdgeInsetsMake(self.imageView.gq_height + 24, 0, 0, 0);
    
//    Regiter the Cell
    [self.tableView registerNib:[UINib nibWithNibName:@"GQRankListCell" bundle:nil] forCellReuseIdentifier:ID];
    
    self.lastOffsetY = self.tableView.contentOffset.y - 20;
    
    //    设置尾部视图
    [self setupFooter];
    
//    发送数据
    [self loadData];

    
}

#pragma mark - 设置尾部视图
- (void)setupFooter
{
    UILabel *label = [[UILabel alloc]init];
    label.gq_height = 35;
    label.textAlignment = UITextAlignmentCenter;
    label.text = @"没有更多";
    
    self.tableView.tableFooterView = label;
}

#pragma mark - 请求数据
- (void)loadData
{
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"from"] = @"android";
    dict[@"version"] = @"5.7.2.0";
    dict[@"channel"] = @"xiaomi";
    dict[@"operator"] = @2;
    dict[@"method"] = @"baidu.ting.billboard.billList";
    dict[@"format"] = @"json";
    dict[@"type"] = @(self.rankItem.type);
    dict[@"offset"] = @0;
    dict[@"size"] = @100;
    dict[@"fields"] = @"song_id";
    dict[@"format"] = @"song_id%2Ctitle%2Cauthor%2Calbum_title%2Cpic_big%2Cpic_small%2Chavehigh%2Call_rate%2Ccharge%2Chas_mv_mobile%2Clearn%2Csong_source%2Ckorean_bb_song";
    
    
    [GQHttpRequest GET:@"http://tingapi.ting.baidu.com/v1/restserver/ting" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        self.billboardItem = [GQRankBillboardItem mj_objectWithKeyValues:responseObject[@"billboard"]];
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:self.billboardItem.pic_s640]];
        self.updateTimeLabel.text = [NSString stringWithFormat:@"更新日期：%@",self.billboardItem.update_date];
        self.Title_Label.text = self.billboardItem.name;
        
        self.itemArrays = [GQRankSongListItem mj_objectArrayWithKeyValuesArray:responseObject[@"song_list"]];
        self.totalSongsLabel.text = [NSString stringWithFormat:@"共%zd首歌",self.itemArrays.count];
        
//        刷新表格
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];

}

//下载按钮
- (IBAction)downloadButtonClick:(UIButton *)sender {
}

//返回按钮
- (IBAction)backButtonClick {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - tableView的数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    self.tableView.tableFooterView.hidden = self.itemArrays.count == 0;
    return self.itemArrays.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GQRankListCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    GQRankSongListItem *songListItem = self.itemArrays[indexPath.row];
    cell.songListItem = songListItem;
    
    return cell;
}

#pragma mark - tableView的代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  
    if (indexPath.row == 0) {
        [self playOnline:@"http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.7.3.0&channel=xiaomi&operator=2&method=baidu.ting.song.getInfos&format=json&songid=264506450&ts=1461681300759&e=42n6ZgLsEm1kMqneK0QZlYpETYxDDyy1UkWIxGXsEucUctcwI1yu3sOGQV1ZX89b&nw=2&ucf=1&res=1&l2p=0&lpb=&usup=1&lebo=0" ];
    } else if (indexPath.row == 1) {
        [self playOnline:@"http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.7.3.0&channel=xiaomi&operator=2&method=baidu.ting.song.getInfos&format=json&songid=264917602&ts=1461681301383&e=CyUluRRfqYig1BkTadUy6B1Eq%2FS0GgqSESlZGNg7QL2OK1TRl5a8WkzNUXDwZUD%2F&nw=2&ucf=1&res=1&l2p=0&lpb=&usup=1&lebo=0"];
    } else {
        [self playOnline:@"http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.7.3.0&channel=xiaomi&operator=2&method=baidu.ting.song.getInfos&format=json&songid=264917164&ts=1461681442916&e=2eReRepWOlbrPVdtRau1kVGPejZdey0DXt%2B8q%2Bwck6T1iNfQmrMFucEJFU6ADWzw&nw=2&ucf=1&res=1&l2p=420&lpb=&usup=1&lebo=0"];
    }

//    改变对应cell的文字颜色
    GQRankListCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell changCellTitleColor:[UIColor blueColor]];

}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
//   还原cell的文本颜色
    GQRankListCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell changCellTitleColor:[UIColor blackColor]];
}

#pragma mark - 发送网络请求播放音乐
- (void)playOnline : (NSString *)onlineUrlString{
    [GQHttpRequest GET:onlineUrlString parameters:nil progress:nil success:^(NSURLSessionDataTask *task, id  _Nullable responseObject) {
        
        //        发送网络请求成功后，播放音乐
        NSArray *tempArray = responseObject[@"songurl"][@"url"];
        NSString *urlString = tempArray[0][@"file_link"];
        
        //    播放音乐
        NSURL *remoteUrl = [NSURL URLWithString:urlString];
        AVPlayerItem *playItem = [AVPlayerItem playerItemWithURL:remoteUrl];
        self.player = [AVPlayer playerWithPlayerItem:playItem];
        [self.player play];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
        
    }];

}

#pragma mark - scrollView代理方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    //    获取滚动的偏移量：（相对于原始的差值）
    CGFloat offsetY = scrollView.contentOffset.y - self.lastOffsetY;

//    获取返回按钮的最大y值
    CGFloat maxY = CGRectGetMaxY(self.backButton.frame);
    self.imageViewConstraint.constant = 200 - offsetY;
    if (self.imageViewConstraint.constant <= maxY) {
        self.imageViewConstraint.constant = maxY;
//        隐藏更新时间label
        self.updateTimeLabel.hidden = YES;
//        显示排行榜名
        self.Title_Label.hidden = NO;
    } else {
        //        显示更新时间label
        self.updateTimeLabel.hidden = NO;
        //        隐藏排行榜名
        self.Title_Label.hidden = YES;
    }
    
    
}
@end
